package org.petstore.web.servlet;

import org.petstore.domain.Account;
import org.petstore.service.CartService;
import org.petstore.util.Cart;
import org.petstore.web.servlet.util.MyUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class RemoveItemFromCartServlet extends HttpServlet {
    private String workingItemId;
    private final CartService cartService = MyUtil.getApplicationContext().getBean("cartService", CartService.class);
    private Cart cart;
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        workingItemId = request.getParameter("workingItemId");
        HttpSession session = request.getSession();
        Account loginUser = (Account) session.getAttribute("loginUser");

        if (workingItemId == null || workingItemId.equals("")) {
            session.setAttribute("message", "购物车内没有该物品");
            request.getRequestDispatcher(ERROR).forward(request, response);

        }
        cartService.deleteInCart(loginUser.getUsername(), workingItemId);
//        ItemDAO itemDAO=new ItemDAOImpl();
//        itemDAO.store(loginUser.getUsername(),cart.getCartItemList());
        //重新获取购物车。
        cart = cartService.getCartByName(loginUser.getUsername());
        session.setAttribute("cart", cart);
        request.getRequestDispatcher(VIEW_CART).forward(request, response);


    }
}
